from fastapi import FastAPI, Depends, HTTPException, status, Body, Request
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from datetime import datetime, timedelta
from typing import Optional
import models
import schemas
from database import SessionLocal, engine
from auth import create_access_token, get_current_user, verify_password, get_password_hash
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError

# 创建数据库表
models.Base.metadata.create_all(bind=engine)

app = FastAPI(title="HongYueAI API")

# 依赖项
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.post("/register", response_model=schemas.User)
def register_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = db.query(models.User).filter(models.User.username == user.username).first()
    if db_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    hashed_password = get_password_hash(user.password)
    db_user = models.User(
        username=user.username,
        hashed_password=hashed_password,
        email=user.email
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = db.query(models.User).filter(models.User.username == form_data.username).first()
    if not user or not verify_password(form_data.password, user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token = create_access_token(data={"sub": user.username})
    return {"access_token": access_token, "token_type": "bearer"}

@app.get("/users/me", response_model=schemas.User)
async def read_users_me(current_user: models.User = Depends(get_current_user)):
    return current_user

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    print(f"422 Validation Error: {exc.errors()}")
    return JSONResponse(
        status_code=422,
        content={"detail": exc.errors(), "body": exc.body},
    )

@app.post("/user/config", response_model=schemas.UserConfigOut)
def save_user_config(
    config: schemas.UserConfigCreate = Body(...),
    db: Session = Depends(get_db),
    current_user: models.User = Depends(get_current_user)
):
    db_config = db.query(models.UserConfig).filter_by(user_id=current_user.id, config_key=config.config_key).first()
    if db_config:
        db_config.config_content = config.config_content
    else:
        db_config = models.UserConfig(user_id=current_user.id, config_key=config.config_key, config_content=config.config_content)
        db.add(db_config)
    db.commit()
    db.refresh(db_config)
    return db_config

@app.get("/user/config/{config_key}", response_model=schemas.UserConfigOut)
def get_user_config(config_key: str, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_user)):
    db_config = db.query(models.UserConfig).filter_by(user_id=current_user.id, config_key=config_key).first()
    if not db_config:
        raise HTTPException(status_code=404, detail="Config not found")
    return db_config

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000) 